import os
import io
import asyncio
import pygame
import sys
import js
from js import document
from pyodide.ffi import create_proxy
from pyodide.http import pyfetch


class GameCore:
    def __init__(self):
        self.run = True
        self.game_paused = False
        self.menu_state = "main"
        self.current_image = None
        self.current_desc = None  # 修改为 current_desc 用于存储描述信息
        self.fonts = {}
        self.buttons = {}
        self.screen = None
        self.clock = None
        self.loader = AssetLoader()
        self.product_images = {
            'fgtp': None,
            'ynm': None,
            'dhzj': None
        }
        self.product_descriptions = {
            'fgtp': "毛细：细如发丝，口感劲道",
            'ynm': "韭叶：宽如韭叶，爽滑入味",
            'dhzj': "大宽：宽如腰带，嚼劲十足"
        }

    async def init(self):
        # 必须先初始化display
        pygame.display.init()
        # 创建窗口后才能初始化其他模块
        self.screen = pygame.display.set_mode((1079, 806))
        pygame.font.init()  # 必须在set_mode之后调用

        # 加载资源
        await self.loader.load_all()

        # 定义颜色
        self.TEXT_COL = (255, 255, 255)
        self.TEXT_COL1 = (0, 0, 205)
        self.TEXT_COL3 = (255, 0, 0)

        # 创建按钮实例
        self.create_buttons()

        # 加载产品介绍图片
        self.product_images['fgtp'] = await self.load_image(self.resource_path("fgtp.png"))
        self.product_images['ynm'] = await self.load_image(self.resource_path("ynm.png"))
        self.product_images['dhzj'] = await self.load_image(self.resource_path("dhzj.png"))

    def resource_path(self, relative):
        # 确保与py-config配置完全一致
        return "assets/" + relative  # 注意这里没有前导斜杠

    async def load_image(self, path):
        try:
            response = await pyfetch(path)
            if response.status != 200:
                raise Exception(f"Failed to fetch image: {path}, status code: {response.status}")
            content = await response.bytes()
            image_stream = io.BytesIO(content)
            return pygame.image.load(image_stream)
        except Exception as e:
            print(f"Error loading image: {e}")
            return None

    def create_buttons(self):
        font = self.loader.fonts["regular"]
        self.resume_button = Button(50, 200, self.create_button_surface(200, 50, "继续游戏", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.options_button = Button(50, 300, self.create_button_surface(200, 50, "制作工艺", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.quit_button = Button(50, 750, self.create_button_surface(200, 50, "退出游戏", font, self.TEXT_COL, (128, 0, 0)), 1)
        self.master_button = Button(50, 500, self.create_button_surface(200, 50, "产品介绍", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.pantiao_button = Button(50, 180, self.create_button_surface(200, 50, "盘面", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.raotiao_button = Button(50, 260, self.create_button_surface(200, 50, "绕条", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.latiao_button = Button(50, 340, self.create_button_surface(200, 50, "拉条", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.shanggan_button = Button(50, 420, self.create_button_surface(200, 50, "上杆", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.xiagan_button = Button(50, 500, self.create_button_surface(200, 50, "下杆", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.baozhuang_button = Button(50, 580, self.create_button_surface(200, 50, "包装", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.back_button = Button(50, 660, self.create_button_surface(200, 50, "返回", font, self.TEXT_COL, (128, 0, 0)), 1)
        self.fgtp_button = Button(50, 200, self.create_button_surface(200, 50, "毛细", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.ynm_button = Button(50, 300, self.create_button_surface(200, 50, "韭叶", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.dhzj_button = Button(50, 400, self.create_button_surface(200, 50, "大宽", font, self.TEXT_COL, (0, 128, 0)), 1)
        self.history_button = Button(50, 400, self.create_button_surface(200, 50, "历史故事", font, self.TEXT_COL, (0, 128, 0)), 1)

    def create_button_surface(self, width, height, text, font, text_color, bg_color):
        surface = pygame.Surface((width, height))
        surface.fill(bg_color)
        text_surface = font.render(text, True, text_color)
        text_rect = text_surface.get_rect(center=(width // 2, height // 2))
        surface.blit(text_surface, text_rect)
        return surface

    def draw_text(self, text, font, text_color, x, y):
        img = font.render(text, True, text_color)
        self.screen.blit(img, (x, y))

    def draw_main_menu(self):
        self.screen.blit(self.loader.blackground1, (0, 0))
        if self.resume_button.draw(self.screen):
            self.game_paused = False
        if self.options_button.draw(self.screen):
            self.menu_state = "options"
        if self.history_button.draw(self.screen):
            self.menu_state = "history"
        if self.master_button.draw(self.screen):
            self.menu_state = "master"
            self.current_image = None
            self.current_desc = None
        if self.quit_button.draw(self.screen):
            self.run = False

    def draw_options_sub_menu(self):
        self.screen.blit(self.loader.blackground2, (0, 0))
        if self.current_image is not None:
            self.screen.blit(self.current_image, (300, 100))
        if self.pantiao_button.draw(self.screen):
            self.current_image = self.loader.pantiao
        if self.raotiao_button.draw(self.screen):
            self.current_image = self.loader.raotiao
        if self.shanggan_button.draw(self.screen):
            self.current_image = self.loader.shanggan
        if self.xiagan_button.draw(self.screen):
            self.current_image = self.loader.xiagan
        if self.latiao_button.draw(self.screen):
            self.current_image = self.loader.latiao
        if self.baozhuang_button.draw(self.screen):
            self.current_image = self.loader.baozhuang
        if self.back_button.draw(self.screen):
            self.menu_state = "main"
            self.current_image = None
            self.current_desc = None

    def draw_master_sub_menu(self):
        self.screen.blit(self.loader.blackground3, (0, 0))

        # 显示当前产品和描述
        if self.current_image:
            image_rect = self.current_image.get_rect(center=(700, 300))
            self.screen.blit(self.current_image, image_rect)

            # 绘制文字背景框
            desc_bg = pygame.Surface((600, 80))
            desc_bg.set_alpha(128)
            desc_bg.fill((0, 0, 0))
            self.screen.blit(desc_bg, (200, 550))

            # 绘制描述文字
            desc_lines = self.current_desc.split('：')
            title = self.loader.fonts["regular"].render(desc_lines[0] + '：', True, (255, 215, 0))
            content = self.loader.fonts["regular"].render(desc_lines[1], True, self.TEXT_COL)
            self.screen.blit(title, (220, 560))
            self.screen.blit(content, (220, 600))

        # 绘制按钮
        if self.fgtp_button.draw(self.screen):
            self.current_image = self.product_images['fgtp']
            self.current_desc = self.product_descriptions['fgtp']
        if self.ynm_button.draw(self.screen):
            self.current_image = self.product_images['ynm']
            self.current_desc = self.product_descriptions['ynm']
        if self.dhzj_button.draw(self.screen):
            self.current_image = self.product_images['dhzj']
            self.current_desc = self.product_descriptions['dhzj']
        if self.back_button.draw(self.screen):
            self.menu_state = "main"
            self.current_image = None
            self.current_desc = None

    def draw_history_sub_menu(self):
        self.screen.blit(self.loader.blackground3, (0, 0))
        if self.back_button.draw(self.screen):
            self.menu_state = "main"
            self.current_image = None
            self.current_desc = None
        self.current_image = self.loader.history_image
        if self.current_image is not None:
            self.screen.blit(self.current_image, (300, 100))
            self.current_image = None
            self.current_desc = None

    async def main_loop(self):
        self.clock = pygame.time.Clock()
        self.run = True

        while self.run:
            self.screen.fill((0, 0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.run = False
                elif event.type == pygame.VIDEORESIZE:
                    self.screen = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.game_paused = not self.game_paused
                    elif event.key == pygame.K_ESCAPE:
                        if self.game_paused:
                            if self.menu_state == "main":
                                self.run = False
                            else:
                                self.menu_state = "main"

            if self.game_paused:
                if self.menu_state == "main":
                    self.draw_main_menu()
                elif self.menu_state == "options":
                    self.draw_options_sub_menu()
                elif self.menu_state == "master":
                    self.draw_master_sub_menu()
                elif self.menu_state == "history":
                    self.draw_history_sub_menu()
            else:
                self.draw_text("按空格键暂停进入菜单", self.loader.fonts["regular"], self.TEXT_COL1, 343, 390)

            pygame.display.update()
            self.clock.tick(60)
            await asyncio.sleep(0)


class AssetLoader:
    def __init__(self):
        self.blackground1 = None
        self.blackground2 = None
        self.blackground3 = None
        self.baozhuang = None
        self.shanggan = None
        self.xiagan = None
        self.latiao = None
        self.pantiao = None
        self.raotiao = None
        self.fgtp = None
        self.ynm = None
        self.dhzj = None
        self.history_image = None
        self.fonts = {}

    async def load_all(self):
        # 图像加载
        self.blackground1 = await GameCore().load_image(GameCore().resource_path("Main Cover.png"))
        self.blackground2 = await GameCore().load_image(GameCore().resource_path("Handmade Desktop.png"))
        self.blackground3 = await GameCore().load_image(GameCore().resource_path("back3.png"))
        self.baozhuang = await GameCore().load_image(GameCore().resource_path("package.png"))
        self.shanggan = await GameCore().load_image(GameCore().resource_path("up.png"))
        self.xiagan = await GameCore().load_image(GameCore().resource_path("down.png"))
        self.latiao = await GameCore().load_image(GameCore().resource_path("push.png"))
        self.pantiao = await GameCore().load_image(GameCore().resource_path("pan.png"))
        self.raotiao = await GameCore().load_image(GameCore().resource_path("rao.png"))
        self.fgtp = await GameCore().load_image(GameCore().resource_path("fgtp.png"))
        self.ynm = await GameCore().load_image(GameCore().resource_path("ynm.png"))
        self.dhzj = await GameCore().load_image(GameCore().resource_path("dhzj.png"))  # 修改为 dhzj.png
        self.history_image = await GameCore().load_image(GameCore().resource_path("history.png"))

        # 字体加载（仅保留一次）
        try:
            font_path = GameCore().resource_path("Regular.ttf")
            print(f"正在加载字体: {font_path}")
            self.fonts["regular"] = pygame.font.Font(font_path, 40)
        except Exception as e:
            print(f"字体加载失败: {str(e)}")
            # 浏览器环境下必须使用以下方式
            self.fonts["regular"] = pygame.font.Font(None, 40)  # 使用默认字体


class Button:
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and not self.clicked:
                self.clicked = True
                action = True
        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False
        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action


async def main():
    game = GameCore()
    await game.init()
    document.getElementById("loading").style.display = "none"
    await game.main_loop()
